package com.highcom.config; // 定义包路径

// 导入必要的Spring Security相关类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

@Configuration // 标记为配置类
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法级安全控制
public class SpringSecurrityConfig extends WebSecurityConfigurerAdapter { // 继承WebSecurity配置适配器

    @Bean // 声明为Spring Bean
    public PasswordEncoder passwordEncoder() { // 密码编码器配置
        // 使用 BCrypt 加密算法
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception { // 配置HTTP安全
        http.formLogin()                   // 配置表单登录
                .loginPage("/pages/login.html")           // 设置登录页面URL
                .loginProcessingUrl("/login"). // 设置登录处理URL
                usernameParameter("username"). // 设置用户名参数名
                passwordParameter("password") .successHandler(successHandler()) // 设置密码参数名和成功处理器
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/pages/login.html").invalidateHttpSession(true).deleteCookies("JESSIONID").and() // 配置登出
                .authorizeRequests()       // 配置请求授权
                .antMatchers("/pages/login.html").permitAll().antMatchers("/pages/mobile/*").permitAll() // 设置无需认证的URL
                .and().authorizeRequests() .antMatchers("/setmeal/getSetmeal","/setmeal/findById","/order/submit","/order/findById","/validateCode/send4Order","/validateCode/send4Login","/member/login").permitAll() // 设置更多无需认证的API
                .anyRequest()               // 其他所有请求
                .authenticated() // 需要认证
                .and().headers().frameOptions().sameOrigin().and() // 配置同源iframe策略
                .csrf().disable();          // 禁用CSRF防护
    }

    @Override
    public void configure(WebSecurity web) throws Exception { // 配置Web安全
        // 设置静态资源不要拦截
        web.ignoring().antMatchers("/css/**","/img/**","/js/**","/plugins/**"); // 忽略静态资源
    }

    SavedRequestAwareAuthenticationSuccessHandler successHandler(){ // 自定义登录成功处理器
        SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
        handler.setDefaultTargetUrl("/pages/main.html"); // 设置默认跳转页面
        handler.setTargetUrlParameter("target"); // 设置目标URL参数
        return handler;
    }
}
